<template>
  <view class="container">
    <!-- 用户积分信息 -->
    <view class="points-info">
      <text class="points-label">当前积分</text>
      <text class="points-value">{{ userPoints }}</text>
    </view>

    <!-- 兑换列表 -->
    <view class="exchange-list">
      <view v-if="exchangeList.length === 0" class="empty-state">
        <text class="empty-text">暂无可兑换的优惠券</text>
      </view>

      <view
        v-else
        v-for="item in exchangeList"
        :key="item.id"
        class="exchange-item"
      >
        <view class="exchange-header">
          <text class="coupon-name">{{ item.couponName }}</text>
          <text class="exchange-status" :class="getStatusClass(item.status)">
            {{ getStatusText(item.status) }}
          </text>
        </view>

        <view class="exchange-content">
          <view class="points-required">
            <text class="points-text">{{ item.points }}</text>
            <text class="points-unit">积分</text>
          </view>

          <view class="exchange-info">
            <text class="exchange-limit"
              >每人限兑{{ item.exchangeLimit }}次</text
            >
            <text class="exchange-time"
              >{{ formatTime(item.startTime) }} -
              {{ formatTime(item.endTime) }}</text
            >
            <text class="exchange-desc">{{ item.description }}</text>
          </view>
        </view>

        <view class="exchange-footer">
          <button
            class="exchange-btn"
            :class="{ disabled: !canExchange(item) }"
            @click="handleExchange(item)"
            :disabled="!canExchange(item)"
          >
            {{ getButtonText(item) }}
          </button>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import http from "@/utils/request";

// 用户积分
const userPoints = ref(0);

// 兑换列表
const exchangeList = ref([]);

// 获取兑换列表
const getExchangeList = async () => {
  try {
    const res = await http.get("/points/exchange/list");
    exchangeList.value = res.data;
  } catch (error) {
    console.error("获取兑换列表失败：", error);
  }
};

// 获取用户积分
const getUserPoints = async () => {
  try {
    const res = await http.get("/points/user/points");
    userPoints.value = res.data;
  } catch (error) {
    console.error("获取积分失败：", error);
  }
};

// 处理兑换
const handleExchange = async (item: any) => {
  if (!canExchange(item)) return;

  uni.showModal({
    title: "确认兑换",
    content: `确定使用${item.points}积分兑换该优惠券吗？`,
    success: async (res) => {
      if (res.confirm) {
        try {
          await http.post("/points/exchange", {
            exchangeId: item.id,
          });
          // 刷新积分和列表
          await Promise.all([getUserPoints(), getExchangeList()]);
          uni.showToast({
            title: "兑换成功",
            icon: "success",
          });
        } catch (error) {
          console.error("兑换失败：", error);
        }
      }
    },
  });
};

// 判断是否可以兑换
const canExchange = (item: any) => {
  const now = new Date().getTime();
  const startTime = new Date(item.startTime).getTime();
  const endTime = new Date(item.endTime).getTime();

  return (
    item.status === 1 && // 已启用
    now >= startTime && // 已开始
    now <= endTime && // 未结束
    userPoints.value >= item.points // 积分足够
  );
};

// 获取状态样式
const getStatusClass = (status: number) => {
  const statusMap: { [key: number]: string } = {
    0: "status-disabled",
    1: "status-active",
    2: "status-ended",
  };
  return statusMap[status] || "";
};

// 获取状态文本
const getStatusText = (status: number) => {
  const statusMap: { [key: number]: string } = {
    0: "未启用",
    1: "可兑换",
    2: "已结束",
  };
  return statusMap[status] || "";
};

// 获取按钮文本
const getButtonText = (item: any) => {
  if (item.status === 0) return "未启用";
  if (item.status === 2) return "已结束";
  if (userPoints.value < item.points) return "积分不足";
  return "立即兑换";
};

// 格式化时间
const formatTime = (time: string) => {
  return time.split(" ")[0];
};

// 页面加载时获取数据
onMounted(() => {
  getUserPoints();
  getExchangeList();
});
</script>

<style>
.container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 20px;
}

.points-info {
  background-color: #ffffff;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 20px;
  text-align: center;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.points-label {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
  display: block;
}

.points-value {
  font-size: 32px;
  color: #ff6b6b;
  font-weight: bold;
}

.exchange-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.empty-state {
  text-align: center;
  padding: 40px 0;
}

.empty-text {
  color: #999;
  font-size: 14px;
}

.exchange-item {
  background-color: #ffffff;
  border-radius: 12px;
  padding: 15px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.exchange-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.coupon-name {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.exchange-status {
  font-size: 12px;
  padding: 4px 8px;
  border-radius: 10px;
}

.status-disabled {
  background-color: #f0f0f0;
  color: #999;
}

.status-active {
  background-color: #e6f7ff;
  color: #1890ff;
}

.status-ended {
  background-color: #fff1f0;
  color: #ff4d4f;
}

.exchange-content {
  display: flex;
  gap: 15px;
  margin-bottom: 15px;
}

.points-required {
  display: flex;
  align-items: baseline;
  gap: 4px;
}

.points-text {
  font-size: 24px;
  color: #ff6b6b;
  font-weight: bold;
}

.points-unit {
  font-size: 14px;
  color: #999;
}

.exchange-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.exchange-limit,
.exchange-time {
  font-size: 12px;
  color: #666;
}

.exchange-desc {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
}

.exchange-footer {
  display: flex;
  justify-content: flex-end;
}

.exchange-btn {
  font-size: 14px;
  padding: 6px 20px;
  border-radius: 15px;
  background-color: #ff6b6b;
  color: #ffffff;
  border: none;
}

.exchange-btn.disabled {
  background-color: #f0f0f0;
  color: #999;
}
</style>
